import config from '@/config'
import { route } from 'uview-plus'
interface RequestConfig {
  url?: string
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'OPTIONS' | 'HEAD' | 'CONNECT' | 'TRACE'
  data?: any
  header?: Record<string, string>
  showLoading?: boolean
  ignoreAuth?: boolean
}

interface Response<T = any> {
  data: T
  statusCode: number
  header: Record<string, string>
}
// import { checkLogin, redirectToLogin } from '@/utils/auth'

// 声明合并扩展自定义配置
// declare module './types' {
//   interface RequestConfig {
//     showLoading?: boolean
//     ignoreAuth?: boolean
//   }
// }

// 统一响应结构
interface ApiResponse<T = any> {
  code: number
  data: T
  msg: string
}

class Request {
  private loadingCount = 0
  private baseURL: string

  constructor() {
    this.baseURL = config.baseURL + '/api'
  }

  private async request<T = any>(config: RequestConfig): Promise<T> {
    // 合并配置
    const mergedConfig: RequestConfig = {
      showLoading: true,
      ignoreAuth: false,
      ...config,
      header: config.header || {}
    }

    try {
      // 请求拦截
      const processedConfig = await this.handleRequestInterceptors(mergedConfig)

      // 显示加载
      if (processedConfig.showLoading) {
        this.showLoading()
      }

      // 发起请求
      const response = await this.uniRequest(processedConfig)

      // 响应拦截处理
      return this.handleResponseInterceptors(response)
    } catch (error) {
      // 错误处理
      return this.handleError(error)
    } finally {
      if (mergedConfig.showLoading) {
        this.hideLoading()
      }
    }
  }

  private async uniRequest(config: RequestConfig): Promise<UniApp.RequestSuccessCallbackResult> {
    return new Promise((resolve, reject) => {
      uni.request({
        url: this.resolveUrl(config.url!),
        method: config.method,
        data: config.data,
        header: config.header,
        success: resolve,
        fail: reject
      })
    })
  }

  private resolveUrl(url: string): string {
    return url.startsWith('http') ? url : `${this.baseURL}${url}`
  }

  private async handleRequestInterceptors(config: RequestConfig): Promise<RequestConfig> {
    config.header!['Accept-Language'] = 'zh-CN'
    config.header!['CONTRACT'] = uni.getStorageSync('CONTRACT') || ''
    // Token 处理 待定暂无与后端确认登录标识
    if (!config.ignoreAuth) {
      const token = uni.getStorageSync('token')
      if (token) {
        config.header!['Authorization'] = `Bearer ${token}`
      } else {
        // redirectToLogin()
      }
    }

    // 可添加其他请求拦截逻辑
    return config
  }

  private handleResponseInterceptors(response: UniApp.RequestSuccessCallbackResult): any {
    const res = response.data as ApiResponse

    if (res.code === -1) {
      console.log('跳转登录页面,待跳转登录页面')
      uni.showModal({
        title: '提示',
        content: res.msg,
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            route({
              url: '/pages_login/login/login'
            })
          }
        }
      })
      throw new Error(res.msg || '请求失败')
    }

    return res.data
  }

  private handleError(error: any): never {
    // const statusCode = error.statusCode || 500
    // let message = '请求错误'

    // switch (statusCode) {
    //   case 400:
    //     message = '请求参数错误'
    //     break
    //   case 401:
    //     message = '登录已过期'
    //     // redirectToLogin()
    //     break
    //   case 500:
    //     message = '服务器错误'
    //     break
    // }

    // uni.showModal({
    //   title: '提示',
    //   content: error,
    //   showCancel: false
    // })

    throw error
  }

  private showLoading() {
    if (this.loadingCount === 0) {
      uni.showLoading({
        title: '加载中',
        mask: true
      })
    }
    this.loadingCount++
  }

  private hideLoading() {
    this.loadingCount--
    if (this.loadingCount <= 0) {
      uni.hideLoading()
      this.loadingCount = 0
    }
  }

  public get<T = any>(url: string, config?: RequestConfig): Promise<T> {
    return this.request({ ...config, method: 'GET', url })
  }

  public post<T = any>(url: string, data?: any, config?: RequestConfig): Promise<T> {
    return this.request({ ...config, method: 'POST', url, data })
  }

  // 其他方法...
}

export default new Request()
